package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取类型列表,并且在redis添加缓存
     *
     * @return
     */
    @Override
    public Object getType() {
        //1.从redis查询类型缓存
        String key = "shop:types";
        String shopTypes = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isNotBlank(shopTypes)) {
            //3.存在，转换为List<ShopType>
            return JSONUtil.toList(shopTypes, ShopType.class);
            //转化为List<ShopType>类型

        }
        //4.不存在，查询数据库
        List<ShopType> typeList = this.query().orderByAsc("sort").list();
        if (typeList == null || typeList.size() == 0) {

            //5.数据库不存在，返回错误
            return Result.fail("没有类型数据");
        }
        //6.将list转换为json格式
        shopTypes = JSONUtil.toJsonStr(typeList);
        //7.数据库存在，写入redis
        stringRedisTemplate.opsForValue().set(key, shopTypes, 30L, TimeUnit.MINUTES);
        //8.返回
        return typeList;
    }
}
